package JDBC;

import Logger.MyLogger;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectionPool {

    private static ConnectionPool connectionPool = null;  //pool per le connessioni
    private ArrayList<Connection> freeConnections; // La coda di connessioni libere
    private String dbUrl;           // Il nome del database
    private String dbDriver;        // Il driver del database
    private String dbUser;         // Il login per il database
    private String dbPassword;      // La password di accesso al database

    //Costruttore privato per assicurare l'utilizzo di getconnectionPool
    private ConnectionPool() throws ConnectionPoolException {
        freeConnections = new ArrayList();
        loadParameters();
        loadDriver();
    }

    public static synchronized ConnectionPool getConnetionPool() throws ConnectionPoolException {
        if (connectionPool == null) {
            connectionPool = new ConnectionPool();
        }
        MyLogger.getLogger().debug("GetConnectionPool");
        return connectionPool;
    }

    private void loadParameters() {
        dbUrl = "jdbc:mysql://localhost:3306/Progetto";
        dbDriver = "com.mysql.jdbc.Driver";
        dbUser = "root";
        dbPassword = "root";
    }

    private void loadDriver() throws ConnectionPoolException {
        try {
            try {
                Class.forName(dbDriver).newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    public synchronized Connection getConnection() throws ConnectionPoolException {
        
        Connection con;
        if(freeConnections.size() > 0){
            con = (Connection) freeConnections.remove(0);
            if(con.isClosed()){
                con = getConnection();
            }
        }
        else{
            con = newConnection();
        }
        MyLogger.getLogger().debug("GetConnection");
        return con;
        
    }

    private Connection newConnection() {
        Connection con = null;
        try {
            con = (Connection) DriverManager.getConnection(dbUrl, dbUser, dbPassword);
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }
    
    public synchronized void relaseConnection (Connection con){
        MyLogger.getLogger().debug("RelaseConnection");
        freeConnections.add(con);        
    }
}
